<template>
  <div class="tabs-box">
    <div>
      <el-button type="primary" @click="clickChange">主动触发切换</el-button>
    </div>
    <el-tabs 
      v-model="activeName" 
      @tab-click="handleClick"
      :before-leave="beforeLeave">
      <el-tab-pane 
        v-for="(item,index) in allTabs" 
        :key="item.name+index" 
        :label="item.label" 
        :name="item.name">
        {{ item.label }}
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        isSaved: false,
        activeName: '1',
        tempName: 'tempName',
        newName: '',
        oldName: '',
        allTabs: [
          {
            label: '用户管理',
            name: '1'
          },
          {
            label: '配置管理',
            name: '2'
          },
          {
            label: '角色管理',
            name: '3'
          },
          {
            label: '定时任务补偿',
            name: '4'
          }
        ]
      };
    },
    methods: {
      clickChange(){
        if(this.activeName>3){
          this.activeName = '1'
        } else {
          this.activeName = String(++this.activeName)
        }
        console.log('0.主动触发：this.activeName',this.activeName);
      },
      beforeLeave(newName, oldName){
        console.log('1.触发钩子',newName, oldName)
        if(newName === this.tempName){
          console.log('5###########--临时名称让其过--#####################');
          return true;
        }
        if(!this.isSaved){
          this.newName = newName;
          this.oldName = oldName;
          this.saveHalder();
          return false;
        } else {
          // 重置保存标记
          this.isSaved = false;
          console.log('4.跳转成功，重置保存标记', this.activeName);
          console.log('###-------------------结束-----------------------###')
          return true;
        }
      },
      switchTab(){
        console.log('3.主动切换this.activeName == this.newName',this.activeName,this.newName, this.activeName === this.newName);
        if(this.activeName === this.newName){
          this.activeName = this.tempName;
          this.$nextTick(()=>{
            this.activeName = this.newName;
          })
        } else {
          this.activeName = this.newName;
        }
      },
      saveHalder(){
        setTimeout(()=>{
          // 保存完毕，主动切换页签
          console.log('2.保存完毕，主动切换页签');
          this.isSaved = true;
          this.switchTab()
        }, 100)
      },
      handleClick(tab, event) {
        console.log('1.点击切换, event');
      }
    }
  };
</script>
<style scoped>
.tabs-box{
  border: 1px solid #ccc;
  margin-top: 10px;
  min-height: 150px;
}
</style>